/*
 * @Author:
 * @Date: 2021-10-15 19:27:10
 * @LastEditors: Please set LastEditors
 * @LastEditTime: 2022-01-21 14:58:46
 * @Description: jwt中间件
 * @FilePath: /bamboo-backend/src/middleware/jwt/index.ts
 */
import Koa from 'koa';
import koaJwt from 'koa-jwt';
import { secret } from '../../config/app';
import { Rcontext } from '../../index';

export function jwtMiddleware(app: Koa) {
  app.use((ctx: Rcontext, next) => {
    // 验证不通过会带上status 401
    return next().catch(err => {
      if (err.status === 401) {
        ctx.sendError(null, -401, '认证失败');
      } else {
        throw err;
      }
    });
  });

  app.use(
    koaJwt({
      secret,
      key: 'jwtData',
    }).unless({
      path: [/\/login$/, /\/upload/], // 匹配到这些路由跳过验证
    })
  );
}
